<template>
    <div class="page" v-loading="loading">
        <div class="page-header flex-row">
            <el-radio-group v-model="network" size="small" class="left-btn" @change="refresh">
                <el-radio-button v-for="item in networks" :label="item.value" :key="item.value">{{ item.label }}</el-radio-button>
            </el-radio-group>
            <div class="flex1"></div>
            <el-button v-if="$auth['operation_task_add']" size="small" @click="toAddTask" type="primary">添加评估任务</el-button>
            <el-popover
                    placement="top-start"
                    title="选择导出列"
                    width="400"
                    v-model="visible"
                    trigger="click"
                    style="margin: 0 15px">
                <div>
                    <el-checkbox-group v-model="checkList">
                        <el-checkbox v-for="item in tableColumn" :key="item.alias" :label="item.name">{{item.alias}}</el-checkbox>
                    </el-checkbox-group>
                    <div class="flex-row">
                        <div class="flex1"></div>
                        <el-button size="small" type="text" @click="exportFile">确定</el-button>
                    </div>
                </div>
                <el-button v-if="$auth['operation_task_export']" slot="reference" size="small">导出</el-button>
            </el-popover>
            <el-button size="small" @click="codeOpen">JSON视图</el-button>
        </div>
        <tz-table
            ref="taskTable"
            highlight-current-row
            size="mini"
            :data="loadData">
            <el-table-column
                    prop="taskName"
                    show-overflow-tooltip
                    label="任务名称">
            </el-table-column>
            <el-table-column
                    prop="modelName"
                    show-overflow-tooltip
                    label="模板名称">
            </el-table-column>
            <el-table-column
                    prop="deviceName"
                    show-overflow-tooltip
                    label="设备名称">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    show-overflow-tooltip
                    label="创建时间"
                    :formatter="(row) => {
                       return row.createTime ? moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'
                     }">
            </el-table-column>
            <el-table-column
                    prop="tag"
                    label="操作">
                <template slot-scope="scope">
                    <el-button @click="toDetail(scope)" size="small" type="text">详情</el-button>
                    <el-button @click="toReport(scope.row)" size="small" type="text">任务报告</el-button>
                    <el-button v-if="$auth['operation_task_delete']" @click="deleteTask(scope)" size="small" type="text">删除</el-button>
                    <el-button v-if="scope.row.status === 1 && $auth['operation_task_status']" @click="switchTask(scope.row)" size="small" type="text">启用</el-button>
                    <el-button v-if="scope.row.status === 0 && $auth['operation_task_status']" @click="switchTask(scope.row)" size="small" type="text">暂停</el-button>
                    <el-button v-if="scope.row.status !== 2 && $auth['operation_task_run']" @click="runNow(scope.row)" size="small" type="text">立即执行</el-button>
                    <span style="margin-left: 10px; color: #cccccc" v-if="scope.row.status === 2">已完成</span>
                </template>
            </el-table-column>
        </tz-table>
        <el-drawer
                size="50%"
                :title="'任务名称：' + currentTask.taskName"
                :visible.sync="drawer">
            <result ref="reportResult" :taskId="currentTask.id"></result>
        </el-drawer>
        <el-drawer
                :title="currentTask.taskName || '添加任务'"
                :visible.sync="detailVisible">
            <taskInfo v-if="detailVisible" ref="taskInfoView" @close="closeDetail"></taskInfo>
        </el-drawer>
        <code-view :codeData="codeData" ref="codeView"></code-view>
    </div>
</template>

<script>
import { networks } from '@/assets/dict'
import tzTable from '@/components/tz-table'
import result from '../result'
import moment from 'moment'
import codeView from '@/components/codeView'
import taskInfo from './taskInfo'
export default {
  name: 'task',
  components: {
    tzTable,
    result,
    codeView,
    taskInfo
  },
  data() {
    return {
      visible: false,
      detailVisible: false,
      loading: false,
      drawer: false,
      network: 'JZW',
      networks,
      moment,
      currentTask: {},
      codeData: [],
      tableColumn: [{
        alias: '任务名称',
        name: 'taskName'
      }, {
        alias: '模板名称',
        name: 'modelName'
      }, {
        alias: '设备名称',
        name: 'deviceName'
      }, {
        alias: '创建时间',
        name: 'createTime'
      }],
      checkList: []
    }
  },
  computed: {
    exportDtoList() {
      return this.tableColumn.filter(item => {
        return this.checkList.includes(item.name)
      })
    }
  },
  methods: {
    closeDetail(refresh) {
      if (refresh) {
        this.refresh()
      }
      this.detailVisible = false
    },
    runNow({jobId}) {
      this.loading = true
      this.$http.post('/sys/schedule/run', {
        jobId
      }).then(() => {
        this.$alert('报告生成中，稍后请在报告列表中查看')
      }).catch(err => {
        this.$TZmessage.error(err.msg || '操作失败')
      }).finally(() => {
        this.loading = false
      })
    },
    codeOpen() {
      this.$refs.codeView.open()
    },
    switchTask(row) {
      let url = '/sys/schedule/pause'
      let name = '暂停'
      if (row.status === 1) {
        url = '/sys/schedule/resume'
        name = '启用'
      }
      this.$confirm(`是否${name}当前任务`).then(res => {
        this.$http.post(url, {
          jobId: row.jobId
        }).then(() => {
          this.$TZmessage.success('操作成功')
        }).catch(err => {
          this.$TZmessage.error(err.msg || '操作失败')
        }).finally(() => {
          this.refresh()
        })
      }).catch(err => {
        console.log('取消执行')
      })
    },
    toReport(row) {
      this.currentTask = row
      this.drawer = true
      this.$refs.reportResult?.refresh()
    },
    exportFile() {
      this.visible = false
      this.$http.post('/evaluate/exportTask', {
        network: this.network,
        exportDtoList: this.exportDtoList
      }, {
        responseType: 'blob',
        headers: {
          'isFileExport': true
        }
      }).then(res => {
        const fileName = `任务列表-${moment().format('YYYY-MM-DD')}.xls`
        let content = res.data; // 文件流
        let blob = new Blob([content]);
        let link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href); // 释放URL 对象
        document.body.removeChild(link);
      })
    },
    refresh() {
      this.$refs.taskTable.refresh(true)
    },
    toAddTask() {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.taskInfoView.init(this.network)
      })
      // this.$router.push({
      //     path: '/operation/task-info',
      //     query: {
      //         network: this.network
      //     }
      // })
    },
    toDetail({row}) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.taskInfoView.init(this.network, row.id)
      })
      // this.$router.push({
      //     path: '/operation/task-info',
      //     query: {
      //         id: row.id
      //     }
      // })
    },
    deleteTask({row}) {
      this.$confirm('是否删除当前任务').then(res => {
        this.loading = true
        this.$http.delete('/evaluate/deleteTask', {
          params: {
            id: row.id
          }
        }).then(() => {
          this.$TZmessage.success('删除成功')
          this.refresh()
        }).catch(err => {
          this.$TZmessage.error(err.msg || '删除失败')
        }).finally(() => {
          this.loading = false
        })
      }).catch(err => {
        console.log('取消执行')
      })
    },
    loadData(res) {
      return this.$http.get('/evaluate/getEvaluateTaskList', {
        params: {
          network: this.network,
          ...res
        }
      }).then(res => {
        this.codeData = {
          data: res.records || [],
          total: res.total
        }
        return this.codeData
      }).catch(err => {
        this.$TZmessage.error(err.msg || '数据加载失败')
      })
    },
  }
}
</script>

<style lang="scss" scoped>
    .page {
        .page-header {
            padding-bottom: 20px;
        }
    }
</style>